package com.wzq.design.business.base.product.service;

import com.wzq.design.base.dto.QueryByIdRequest;
import com.wzq.design.base.service.CommService;
import com.wzq.design.business.base.product.dto.BaseProductDto;
import com.wzq.design.business.base.product.dto.ProductRequest;
import com.wzq.design.business.base.product.entity.BaseProduct;
import com.wzq.design.business.base.product.mapper.ProductMapper;
import com.wzq.ssm.parent.base.dto.Page;
import com.wzq.ssm.parent.util.EntityUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangzhiqiang
 * @since 2023/5/8 15:05
 */
@Service
public class ProductService extends CommService<ProductMapper, BaseProduct> {

    private final ProductMapper productMapper;


    public ProductService(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Transactional
    public BaseProductDto save(BaseProductDto dto) {
        BaseProduct sysProduct;
        if (StringUtils.isBlank(dto.getId())) {
            sysProduct = EntityUtil.castDtoToModel(dto, BaseProduct.class);

            productMapper.insert(sysProduct);
        } else {
            sysProduct = productMapper.selectById(dto.getId());
            EntityUtil.copyDtoToBean(dto, sysProduct);
            productMapper.updateById(sysProduct);
        }

        return BaseProductDto.fromDb(sysProduct);
    }


    public Page<BaseProductDto> list(ProductRequest productRequest) {
        List<BaseProduct> sysProducts = productMapper.list(productRequest);
        return Page.create(productRequest, sysProducts.stream().map(BaseProductDto::fromDb).collect(Collectors.toList()));
    }


    public BaseProductDto findById(QueryByIdRequest userRequest) {
        BaseProduct sysProduct = productMapper.selectById(userRequest.getId());
        return BaseProductDto.fromDb(sysProduct);
    }

}
